package mrusanov.ui.stats

import javax.swing.{ JComboBox, DefaultComboBoxModel, JPanel }
import java.awt.FlowLayout
import mrusanov.util.swing.{ Event, EventProducer }
import java.awt.event.{ ActionEvent, ActionListener }

class ComboBoxTreeHandlerPanel(root: TreeNode)
	extends JPanel with EventProducer[JPanel] {
	private var _selection: Vector[Int] = Vector()

	setLayout(new FlowLayout())

	def selection = _selection
	def selection_=(selection: Vector[Int]) {
		_selection = addObviousSelections(selection)
		buildComboBoxes()
	}

	private def addObviousSelections(initial: Vector[Int]): Vector[Int] = {
		var currentNode = root
		for (i <- initial) {
			currentNode = currentNode.children(i)
		}

		var obviousSelections = Vector[Int]()
		while (currentNode.children.size == 1) {
			obviousSelections :+= 0
			currentNode = currentNode.children(0)
		}

		initial ++ obviousSelections
	}

	private def buildComboBoxes() {
		removeAll()
		var currentNode = root
		for (i <- 0 to _selection.size) {
			val selectedIndex = if (_selection.size > i) _selection(i) else -1
			addComboBox(currentNode, selectedIndex, _selection.take(i))

			if (_selection.size > i) {
				currentNode = currentNode.children(_selection(i))
			}
		}

		if (currentNode.isInstanceOf[TreeLeaf]) {
			val leaf = currentNode.asInstanceOf[TreeLeaf]
			notifyConsumers(leaf.panel)
		}

		revalidate();
	}

	private def addComboBox(node: TreeNode, selectedIndex: Int, selectionPart: Vector[Int]) {
		val model = new DefaultComboBoxModel
		node.children.foreach(model.addElement(_))
		val comboBox = new JComboBox()
		comboBox.setModel(model)
		comboBox.setSelectedIndex(selectedIndex)
		comboBox.addActionListener(new ActionListener {
			def actionPerformed(e: ActionEvent) {
				val newSelection = selectionPart :+ comboBox.getSelectedIndex
				ComboBoxTreeHandlerPanel.this.selection = newSelection
			}
		})
		add(comboBox)
	}
}
